package com.itboye.ihomebank.me.key;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.BeiFenKeyAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.BeiFenKeyBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.db.KeyService;
import com.itboye.ihomebank.key.ActivityGuanLiKeyTwo;
import com.itboye.ihomebank.key.ActivityKeySouSuo;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.sliblistview.SwipeMenu;
import com.itboye.ihomebank.sliblistview.SwipeMenuCreator;
import com.itboye.ihomebank.sliblistview.SwipeMenuItem;
import com.itboye.ihomebank.sliblistview.SwipeMenuListView;
import com.itboye.ihomebank.sliblistview.SwipeMenuListView.OnMenuItemClickListener;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;

/**
 * 备份钥匙
 * 
 */
public class ActivityMyKey extends BaseOtherActivity implements Observer {
	ImageView close_icon;// 返回图片
	TextView add_shap_title_tv;// 标题
	EditText mykey_sousuo;
	TextView img_nodata;
	SwipeMenuListView xlistview;
	
	KeyPresenter keyPresenter;
	private List<BeiFenKeyBean> keyBean;
	BeiFenKeyAdapter adapter;
	
	String uid;
	String lockid;
	String keyId;
	
	KeyService keyService;
	
	BeiFenKeyBean bean=new BeiFenKeyBean();
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.close_icon:
			finish();
			break;
		case R.id.mykey_sousuo:
			Intent intent=new Intent(this, ActivityKeySouSuo.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	protected int layout_id() {
		return R.layout.activity_my_key;
	}

	@Override
	protected void onInitController() {
		keyPresenter=new KeyPresenter(this);
		uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
		keyService=new KeyService(this);
		
		List<BeiFenKeyBean> userlist=keyService.getAllUserList();
		if(null!=userlist&&userlist.size()>0){//当数据库中有数据的话  从数据库中读取
        	adapter = new BeiFenKeyAdapter(ActivityMyKey.this,
        			getData(), R.layout.item_my_key);
			xlistview.setAdapter(adapter);
        }else{
        	showProgressDialog("数据加载中,请稍后", true);
    		keyPresenter.getBeifeiList(uid);
        }
		
		
		//删除钥匙
		xlistview.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public void onMenuItemClick(int position, SwipeMenu menu, int index) {
				showProgressDialog("正在删除,请稍后", true);
				keyId=keyBean.get(position).getKeyId();
				keyPresenter.getDeleteBeiFen(uid, keyBean.get(position).getLockId(), keyBean.get(position).getKeyId());
			}
		});
		
		xlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(ActivityMyKey.this,
						ActivityGuanLiKeyTwo.class);
				intent.putExtra("lockid", keyBean.get(position).getLockId());
				intent.putExtra("keyid",keyBean.get(position).getKeyId());
				intent.putExtra("lockMac",keyBean.get(position).getLockMac());
				intent.putExtra("lockAlias", keyBean.get(position).getLockAlilas());
				startActivity(intent);

			}
		});

	}

	@Override
	protected void onInit() {
		add_shap_title_tv.setText("我的备份钥匙");
		//li_search.setVisibility(View.GONE);
		
		setCreator();
	}
	//查询钥匙页面返回后，重新加载listView
	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 103) {
			String lock_alias=data.getStringExtra("lock_alias");
			List<BeiFenKeyBean> b=new ArrayList<BeiFenKeyBean>();
			b=(List<BeiFenKeyBean>) keyService.aliasQuery(lock_alias);
			adapter = new BeiFenKeyAdapter(ActivityMyKey.this,
					b, R.layout.item_my_key);
			xlistview.setAdapter(adapter);
		}
	}
	

	@Override
	protected void onReadIntent(Bundle bundle) {
		
	}
	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}
	private void setCreator() {

		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// TODO Auto-generated method stub
				SwipeMenuItem item2 = new SwipeMenuItem(ActivityMyKey.this);
				item2.setBackground(new ColorDrawable(Color.rgb(0xff, 0x6e,
						0xa5)));
				item2.setWidth(dp2px(90));
				item2.setTitle("删除钥匙");
				item2.setTitleSize(18);
				item2.setTitleColor(Color.parseColor("#ffffff"));
				// item2.setIcon(R.drawable.ic_action_discard);
				menu.addMenuItem(item2);
			}
		};
		xlistview.setMenuCreator(creator);
	}
	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
		if (entity != null) {
			if (entity.getEventType() == KeyPresenter.beifenList_success) {
				keyBean = (List<BeiFenKeyBean>) entity.getData();
				if (keyBean != null) {
					if (keyBean.size() > 0) {
						adapter = new BeiFenKeyAdapter(ActivityMyKey.this,
								keyBean, R.layout.item_my_key);
						xlistview.setAdapter(adapter);
						
						BeiFenKeyBean beans=new BeiFenKeyBean();
						for (int i = 0; i < keyBean.size(); i++) {
							beans.setLockId(keyBean.get(i).getLockId());
							beans.setKeyId(keyBean.get(i).getKeyId());
							beans.setLockMac(keyBean.get(i).getLockMac());
							beans.setLockAlilas(keyBean.get(i).getLockAlilas());
							
							keyService.add(beans);//存放到数据库
						}
						
						img_nodata.setVisibility(View.GONE);
						xlistview.setVisibility(View.VISIBLE);
					}else{
						img_nodata.setVisibility(View.VISIBLE);
						img_nodata.setText("没有钥匙哦...");
						xlistview.setVisibility(View.GONE);
					}
				}else {
						img_nodata.setText("没有钥匙哦...");
						img_nodata.setVisibility(View.VISIBLE);
						xlistview.setVisibility(View.GONE);
				}
			}
			if(entity.getEventType() == KeyPresenter.beifenList_fail){
				ByAlert.alert(entity.getData());
			}
			if(entity.getEventType() == KeyPresenter.deleteBeifen_success){
				ByAlert.alert(entity.getData());
				Iterator<BeiFenKeyBean> iterator = keyBean.iterator();
				while (iterator.hasNext()) {
					BeiFenKeyBean bean = iterator.next();
					if (keyId.equals(bean.getKeyId())) {
						iterator.remove();
						adapter.notifyDataSetChanged();
						break;
					}
				}
			}
			if(entity.getEventType() == KeyPresenter.deleteBeifen_fail){
				ByAlert.alert(entity.getData());
			}
		}
	}
	/**
     * 从数据库读取listview数据
     * @return
     */
    private List<BeiFenKeyBean> getData() {
    	keyBean = new ArrayList<BeiFenKeyBean>();
        
        List<BeiFenKeyBean> userlist=keyService.getAllUserList();
        if(null!=userlist&&userlist.size()>0){
        	for(int i=0;i<userlist.size();i++){
        		BeiFenKeyBean beans=new BeiFenKeyBean();
        		beans.setLockId(userlist.get(i).getLockId());
        		beans.setKeyId(userlist.get(i).getKeyId());
        		beans.setLockMac(userlist.get(i).getLockMac());
        		beans.setLockAlilas(userlist.get(i).getLockAlilas());
        		keyBean.add(beans);
        	}
        }
        return keyBean;
    }
}
